package com.ly.ocw.service.weixin;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springside.modules.mapper.JsonMapper;

import com.ly.ocw.comm.DateUtil;
import com.ly.ocw.entity.weixin.WeixinCardApiTicket;
import com.ly.ocw.entity.weixin.WeixinCardApiTicketLog;
import com.ly.ocw.exception.ServerException;
import com.ly.ocw.repository.weixin.WeixinCardApiTicketDao;
import com.ly.ocw.repository.weixin.WeixinCardApiTicketLogDao;
import com.ly.ocw.rest.dto.card.CardApiTicketDto;
import com.ly.ocw.utils.HttpUtil;

/**
 * 
 * 
 * @author Peter
 */
// Spring Service Bean的标识.
@Component
public class WeixinCardApiTicketService {

	private static Logger logger = LoggerFactory.getLogger(WeixinCardApiTicketService.class);
	private static JsonMapper mapper = JsonMapper.nonDefaultMapper();

	@Autowired
	private WeixinConf weixinConf;
	
	@Autowired
	private WeixinAccessTokenService weixinAccessTokenService;
	
	@Autowired
	private WeixinCardApiTicketDao weixinCardApiTicketDao;
	
	@Autowired
	private WeixinCardApiTicketLogDao weixinCardApiTicketLogDao;


	public String getCardApiTicket() throws ServerException {
		WeixinCardApiTicket weixinCardApiTicket = weixinCardApiTicketDao.getByWeixinPublicId(weixinConf.getPublicId());
		if (weixinCardApiTicket == null) {
			// 数据库中没有AccessToken信息，从微信服务器获取AccessToken
			CardApiTicketDto dto = receiveCardApiTicket();
			weixinCardApiTicket = dtoToEntity(dto);
			WeixinCardApiTicketLog log = dtoToEntityLog(dto);
			
			weixinCardApiTicketDao.save(weixinCardApiTicket);
			weixinCardApiTicketLogDao.save(log);
			
		} else {
			// 判断是否过期
			if (DateUtil.isExpires(weixinCardApiTicket.getUpdateDate(),weixinCardApiTicket.getExpiresIn().intValue())){
				logger.info("过期：access_token  "+DateUtil.sdf_1.format(weixinCardApiTicket.getUpdateDate()));
				//过期，重新获取ticket
				Long id = weixinCardApiTicket.getId();
				CardApiTicketDto dto = receiveCardApiTicket();
				weixinCardApiTicket = dtoToEntity(dto);
				weixinCardApiTicket.setId(id);
				WeixinCardApiTicketLog log = dtoToEntityLog(dto);
				weixinCardApiTicketDao.update(weixinCardApiTicket);
				weixinCardApiTicketLogDao.save(log);
			}

		}
		return weixinCardApiTicket.getApiTicket();
	}
	
	private CardApiTicketDto receiveCardApiTicket() throws ServerException {
		String accessToken = weixinAccessTokenService.getAccessToken();
		// https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card
		// https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=MJgGXlhZHa5m4O1Z3oN-xWnL_F50tYOL0vjwfLmTE5zmu5wZWPyIm1mllpzv96mBeapohNxELISpCsEAthXtZrgZupPaVmRE2sOqzEijDSI&type=wx_card
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=wx_card";

		String body = HttpUtil.httpGet(url);
		CardApiTicketDto dto = mapper.fromJson(body, CardApiTicketDto.class);

		if (!"0".equals(dto.getErrcode())) {
			throw new ServerException(dto.getErrcode(), dto.getErrmsg());
		}
		return dto;
	}


	private WeixinCardApiTicket dtoToEntity(CardApiTicketDto dto) {
		WeixinCardApiTicket ticket = new WeixinCardApiTicket();
		ticket.setApiTicket(dto.getTicket());
		ticket.setExpiresIn(Long.parseLong(dto.getExpires_in()));
		ticket.setCreateDate(new Date());
		ticket.setUpdateDate(new Date());
		ticket.setWeixinPublicId(weixinConf.getPublicId());
		return ticket;
	}

	private WeixinCardApiTicketLog dtoToEntityLog(CardApiTicketDto dto) {
		WeixinCardApiTicketLog log = new WeixinCardApiTicketLog();

		if (!"0".equals(dto.getErrcode())) {
			log.setErrcode(dto.getErrcode());
			log.setErrmsg(dto.getErrmsg());
		}else{
			log.setJsapiTicket(dto.getTicket());
			log.setExpiresIn(Long.parseLong(dto.getExpires_in()));
		}

		log.setCreateDate(new Date());
		log.setWeixinPublicId(weixinConf.getPublicId());
		return log;
	}}
